<?php

namespace App\Library;

use App\Traits\GuzzleHttpTrait;
use Exception;
use Throwable;

class BaseApi
{

    use GuzzleHttpTrait;

    /**
     * 接口返回码
     */
    const CODE_SUCCESS = 200;    // 成功

    /**
     * 获取地址
     */
    protected function getDomain(): string
    {
        return '';
    }

    /**
     * 加工url
     *
     * @param string $api
     * @return string
     */
    protected function makeUrl(string $api): string
    {
        return $this->getDomain() . $api;
    }

    /**
     * post 请求
     *
     * @param string $url
     * @param array $params
     * @return array
     * @throws Exception
     */
    public function curlNativePost(string $url, array $params = []): array
    {
        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params)); // 发送 JSON 数据
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Authorization: Bearer your_token',
                'Content-Type: application/json', // 设置为 JSON 格式
                'Accept: application/json',
            ]);

            $response = curl_exec($ch);

            if (curl_errno($ch)) {
                $message = curl_error($ch);
                curl_close($ch);
                throw new Exception($message);
            } else {
                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);
                if ($httpCode === 200) {
                    return json_decode($response, true);
                } else {
                    throw new Exception($httpCode);
                }
            }

        } catch (Throwable $ex) {
            throw new Exception('接口返回失败:errMsg=' . $ex->getMessage());
        }
    }

    /**
     * post 请求
     *
     * @param string $url
     * @param array $params
     * @param bool $origin
     * @return array|mixed
     * @throws Exception
     */
    public function curlPost(string $url, array $params = [], bool $origin = false)
    {
        try {
            return $this->guzzleHttpPost($url, $params, $origin);
        } catch (Throwable $ex) {
            throw new Exception('接口返回失败:errMsg=' . $ex->getMessage());
        }
    }

    /**
     * get 请求
     *
     * @param string $url
     * @param array $query
     * @param bool $origin
     * @return array|mixed
     * @throws Exception
     */
    public function curlGet(string $url, array $query = [], bool $origin = false)
    {
        try {
            return $this->guzzleHttpGet($url, $query, $origin);
        } catch (Throwable $ex) {
            throw new Exception('接口返回失败:errMsg=' . $ex->getMessage());
        }
    }
}
